package com.fingard.text;

public class XmlHelper {
	
	//编码xml特定字符
	public static String encode(String value){
		if(value == null || value.length() == 0){
			return "";
		}
		int len = value.length();
		StringBuilder sb = null;
		for(int i=0;i<len;i++){
			char tmpChar = value.charAt(i);
			if(tmpChar == '<' || tmpChar == '>' || tmpChar == '&'){
				if(sb == null){
					sb = new StringBuilder();
					sb.append(value.substring(0, i));
				}
				if(tmpChar == '<'){
					sb.append("&lt;");
				}
				else if(tmpChar == '>'){
					sb.append("&gt;");
				}
				else if(tmpChar == '&'){
					sb.append("&amp;");
				}
			}
			else if(sb != null){
				sb.append(tmpChar);
			}
		}
		if(sb == null){
			return value;
		}
		else{
			return sb.toString();
		}
	}
	
	public static String encodeFull(String value){
		if(value == null || value.length() == 0){
			return "";
		}
		int len = value.length();
		StringBuilder sb = null;
		for(int i=0;i<len;i++){
			char tmpChar = value.charAt(i);
			if(tmpChar == '<' || tmpChar == '>' || tmpChar == '"' || tmpChar == '\'' || tmpChar == '&'){
				if(sb == null){
					sb = new StringBuilder();
					sb.append(value.substring(0, i));
				}
				if(tmpChar == '<'){
					sb.append("&lt;");
				}
				else if(tmpChar == '>'){
					sb.append("&gt;");
				}
				else if(tmpChar == '"'){
					sb.append("&quot;");
				}
				else if(tmpChar == '\''){
					sb.append("&apos;");
				}
				else if(tmpChar == '&'){
					sb.append("&amp;");
				}
			}
			else if(sb != null){
				sb.append(tmpChar);
			}
		}
		if(sb == null){
			return value;
		}
		else{
			return sb.toString();
		}
	}
}
